package org.sunrise.game.client.main;

import com.alibaba.fastjson.JSONArray;
import org.sunrise.game.client.client.SocketClient;
import org.sunrise.game.client.client.SocketClientManager;
import org.sunrise.game.client.gen.LoginProto;
import org.sunrise.game.client.gen.TopicProto;
import org.sunrise.game.common.log.LogCore;

public class LoginManager {

    public static String httpUrl = "127.0.0.1:8080";

    public static void login(SocketClient client) {
        // 获取一个game服务器id
        int id = JSONArray.parseObject(client.curl("http://" + httpUrl + "/game_id?uid=" + client.getUid())).getIntValue("server_id");
        LogCore.Client.info("Request game_id success, data = {}", id);
        if (id <= 0) {
            return;
        }

        // 获取一个对外服务器地址
        String address = JSONArray.parseObject(client.curl("http://" + httpUrl + "/external_address?type=" + SocketClientManager.socketType)).getString("address");
        LogCore.Client.info("Request external_address success, data = {}", address);
        if (address.isEmpty()) {
            return;
        }
        String[] split = address.split(":");
        String ip = split[0];
        int port = Integer.parseInt(split[1]);

        client.setConnectId(id);
        client.connect(ip, port);

        while (true) {
            if (client.isConnectSuccess()) {
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        client.sendMsg(TopicProto.MBasePacketData.newBuilder()
                .setPacketType(TopicProto.TOPIC.TOPIC_TYPE_LOGIN)
                .setPacketId(LoginProto.FROM_CLIENT.C2S_Login_VALUE)
                .setPacketData(LoginProto.MC2S_Login.newBuilder().setUid(client.getUid()).build().toByteString())
                .build());
        client.setLoginStartTime(System.currentTimeMillis());
    }
}
